import React from 'react';
import { Form } from '@ant-design/compatible';
import AuthComponent from '@/components/Authorized/AuthComponent';
import '@ant-design/compatible/assets/index.css';
import { Modal, Descriptions, Divider, Button, Collapse } from 'antd';
import Zmage from 'react-zmage'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'
import style from './ListofDetail.less';
import { useRequest } from '@umijs/hooks';
import { queryDdetails,getConfigInfo } from '../service';
import router from 'umi/router'
import {API_URL} from '@/config/api'

const { Panel } = Collapse;
const ListofDetails = props => { 
  const { modalVisible, onCancel, overId} = props;

  const flilterIDtype = v => {
    if (v === 'NI') {
      return <span>身份证</span>;
    } else if (v === 'PP' || v === 'PSPT') {
      return <span>护照</span>;
    } else {
      return <span>其他</span>;
    }
  };

  const toOrderId = (value) => {
    let indemnityFormState = {
      type: 'examine',
      orderId:value,
      status: '4'
    };
    window.localStorage.setItem('indemnityFormBackUrl','/compensation/oversaleindex');
    window.localStorage.setItem('indemnityFormState',JSON.stringify(indemnityFormState));
    router.push({
      pathname: '/compensation/indemnityForm',
      state: indemnityFormState
    })
    //路由跳转至补偿模块的详情基本信息页面
  }
  // 导出PDF文件
  const exportPdf = () => {
      html2canvas(document.getElementById("exportPdfInfo"),{
        dpi: 300,//导出pdf清晰度
        scale: 2, //按比例增加分辨率 2：2倍
        useCORS:true, //保证跨域图片的加载
      }).then(canvas => {
        // 不分页
         /**jspdf将html转为pdf一页显示不截断，整体思路：
         * 1. 获取DOM 
         * 2. 将DOM转换为canvas
         * 3. 获取canvas的宽度、高度（稍微大一点）
         * 4. 将pdf的宽高设置为canvas的宽高
         * 5. 将canvas转为图片
         * 6. 实例化jspdf，将内容图片放在pdf中（因为内容宽高和pdf宽高一样，就只需要一页，也防止内容截断问题）
         */

        // 得到canvas画布的单位是px 像素单位
        var contentWidth = canvas.width
        var contentHeight = canvas.height
        // 将canvas转为base64图片
        var pageData = canvas.toDataURL('image/jpeg', 1.0)
        // 设置pdf的尺寸，pdf要使用pt单位 已知 1pt/1px = 0.75   pt = (px/scale)* 0.75
        // 2为上面的scale 缩放了2倍
        var pdfX = (contentWidth + 10) / 2 * 0.75
        var pdfY = (contentHeight + 500) / 2 * 0.75 // 500为底部留白

        // 设置内容图片的尺寸，img是pt单位 
        var imgX = pdfX;
        var imgY = (contentHeight / 2 * 0.75); //内容图片这里不需要留白的距离

        // 初始化jspdf 第一个参数方向：默认''时为纵向，第二个参数设置pdf内容图片使用的长度单位为pt，第三个参数为PDF的大小，单位是pt
        var PDF = new jsPDF('', 'pt', [pdfX, pdfY])

        // 将内容图片添加到pdf中，因为内容宽高和pdf宽高一样，就只需要一页，位置就是 0,0
        PDF.addImage(pageData, 'jpeg', 0, 0, imgX, imgY)
        PDF.save(`${detailsdata?.paxName}_${detailsdata?.flightNo}_超售事故单_${detailsdata?.overId}.pdf`);
      })
  }

  // const { data: detailsdata, loading: detailLoading } = useRequest(() => queryDdetails(orderId))
  const { data: detailsdata={}, loading: detailLoading } = useRequest(() => queryDdetails({'overId':overId}),
    {
      refreshDeps: [overId],
      initialData:{}
    }
  )

  const { data: rulesdata={timeDifferenceInfo:[],lowestStandInfo:{},refundInfo:{}}, loading: rulesLaoding } = useRequest(getConfigInfo)
  return!detailLoading && !rulesLaoding &&
        <Modal
        getContainer = {() => document.getElementById('oversaleIndexId')}
        maskStyle = {{position:"absolute"}}
        wrapClassName= {style.listDetailWrapStyle}
        style={{top: 0,width: '100%',marginRight:0,buttom:0,paddingBottom: 0}}
        destroyOnClose
        title={<div>旅客信息 <Button style={{marginLeft:"30px"}} type="primary" onClick={exportPdf}>导出PDF</Button></div>}
        visible={modalVisible}
        bodyStyle={{padding:'0'}}
        footer={null}
        onCancel={() => onCancel()}
    >
    <div id="exportPdfInfo" style={{padding:"24px"}}>
        <Descriptions title={detailsdata.paxName} column={1}>
          <Descriptions.Item label="客票号码">{detailsdata.tktNo}</Descriptions.Item>
          <Descriptions.Item label="证件类型">
            {flilterIDtype(detailsdata.idType)}
            {/* {detailsdata.idType === '1' ?'身份证' : '其他'} */}
          </Descriptions.Item>
          <Descriptions.Item label="证件号码">{detailsdata.idNo}</Descriptions.Item>
          <Descriptions.Item label="联系电话">{detailsdata.telephone}</Descriptions.Item>
        </Descriptions>
        <Divider />
        <Descriptions title={<span>航班信息：
            <Button style={{background:'rgba(225, 59, 59, 0.35)',color:'#E13B3B',border:'1px solid',height:'21px',padding:'0 8px'}}>
            {detailsdata.type === '0' ? '改签' : null}
            {detailsdata.type === '1' ? '退票' : null}
            </Button></span>} column={2}>
            <Descriptions.Item label="航段">{detailsdata.segment}</Descriptions.Item>
            <Descriptions.Item label="航班日期">{detailsdata.flightDate}</Descriptions.Item>
            <Descriptions.Item label="原始航班">{detailsdata.flightNo}</Descriptions.Item>
            <Descriptions.Item label="计划起飞时间">{detailsdata.oldPlaneDate}</Descriptions.Item>
            <Descriptions.Item label="改签航班">{detailsdata.overBookFlightNo}</Descriptions.Item>
            <Descriptions.Item label="改签日期">{detailsdata.overBookFlightDate}</Descriptions.Item>
            <Descriptions.Item label="改签时间">{detailsdata.planeDate}</Descriptions.Item>
            <br></br>
            <Descriptions.Item label="附件照片" span={4}>
              {/* 图片路径 */}
               {
                   detailsdata.imgUrl&&detailsdata.imgUrl!==null?
                   <div style={{display: 'flex',
                       justifyContent: 'flex-start',
                       alignItems: 'center',
                       flexWrap: 'wrap'}}>{
                        detailsdata.imgUrl.split(',').map(function(item,index,arr){
                        let imgurl=`${API_URL}/api/uploadAndDownload/showImg?imgUrl=${item}`
                          //                     let imgurl='http://172.16.1.206:81/api/uploadAndDownload/showImg?imgUrl=' + item
                             return <div style={{display: 'block',width:'140px',height:'140px',margin:'5px'}}><Zmage src={imgurl} style={{display: 'block',width:'100%',height:'100%'}}/></div>
                          //  <img src={imgurl} alt="" style={{display: 'block',width:'140px',height:'140px',margin:'5px'}}/>
                       })
                     }</div>
                    :'-'
                }
            </Descriptions.Item>

        </Descriptions>
        <Divider />
        <Descriptions title={<span >补偿信息：<Button type='link' style={{marginLeft:'50%'}}></Button></span>} column={1}>
          <Descriptions.Item  className={style.rules}>
            <Collapse style={{fontSize:'12px'}}>
              <Panel header="查看补偿规则" key="1" style={{fontSize:'12px',color:'#E13B3B'}}>
                <p> 补偿规则：
                  <br/>
                    <b>1.旅客改签：</b>
                    <br/>
                    {rulesdata.timeDifferenceInfo&&rulesdata.timeDifferenceInfo.map(i => (
                      <span>改签航班时差{i.leftConditionValue}小时 &lt;= 延误时长  {i.conditionValue ? '<' + i.conditionValue : ''}按原航班全票价{i.damagePart}%
                      {i.payMoney ? ' 或 ' + i.payMoney + '元' : ''} 赔付<br/></span>
                    ))}
                    <br/>
                    改签航班时差：改签新航班计划起飞时间-原航班计划起飞时间
                    <br/>
                    <br/>
                    <b>2.旅客退票：</b>
                    <br/>
                    {
                      rulesdata.refundInfo && rulesdata.refundInfo.payMoney
                      ? <span>不区分舱等和票价，均按{rulesdata.refundInfo.payMoney}元赔付</span>
                      : ''
                    }
                    
                    <br/>
                  </p>
              </Panel>
            </Collapse>
          </Descriptions.Item>
          <Descriptions.Item label="总金额">{detailsdata.sumMoney}</Descriptions.Item>
          <Descriptions.Item label="补偿金额">{detailsdata.payMoney}</Descriptions.Item>
          <Descriptions.Item label="原票价">{detailsdata.price}</Descriptions.Item>
          <Descriptions.Item label="领取状态">
            {detailsdata.receiveStatus==='0'?'未领取':(detailsdata.receiveStatus==='')}
            {detailsdata.receiveStatus==='1'?'已领取':(detailsdata.receiveStatus==='')}
            {detailsdata.receiveStatus==='2'?'处理中':(detailsdata.receiveStatus==='')}
          </Descriptions.Item>
          {/* 点击补偿单号，跳转至补偿页面模块，补偿单详情*/}
          <Descriptions.Item label="补偿单号"><span style={{cursor:'pointer',textDecoration:'underline',color:'#E13B3B'}} onClick={() => toOrderId(detailsdata.orderId)}>{detailsdata.orderId}</span></Descriptions.Item>
        </Descriptions>
      </div>
    </Modal>
};

export default Form.create()(ListofDetails);
